// src/router/index.ts

import {createRouter, createWebHistory, type RouteRecordRaw} from 'vue-router'
import LoginView from '../components/login.vue'
import IndexView from '../components/index.vue'
import NProgress from 'nprogress';
import 'nprogress/nprogress.css'
// 导入 userStore
import {useUserStore} from '../stores/userStore.ts'

const routes: RouteRecordRaw[] = [
    {
        path: '/login',
        name: 'Login',
        component: LoginView,
        meta: {requiresAuth: false}
    },
    {
        path: '/main',
        name: 'Index',
        component: IndexView,
        meta: {requiresAuth: true},
        children: [
            {
                path: 'home',
                component: () => import('../views/homePage.vue'),
                meta: {
                    title: '首页',
                    roles: ['admin', 'teacher', 'student'] 
                }
            },
            {
                path: 'about',
                component: () => import('../views/aboutPage.vue'),
                meta: {
                    title: '关于',
                    roles: ['admin', 'teacher', 'student'] 
                }
            },


            {
                path: 'examSchedule',
                component: () => import('../views/examSchedule.vue'),
                meta: {
                    title: '考试安排',
                    roles: ['admin', 'student'] 
                }
            },
            {
                path: 'takeExam',
                component: () => import('../views/takeExam.vue'),
                meta: {
                    title: '参加考试',
                    roles: ['admin', 'student'] 
                }
            },
            {
                path: 'ViewGrades',
                component: () => import('../views/ViewGrades.vue'),
                meta: {
                    title: '查看成绩',
                    roles: ['admin','student'] 
                }
            },

            {
                path: 'createExamSchedule',
                component: () => import('../views/createExamSchedule/index.vue'),
                meta: {
                    title: '创建考试安排',
                    roles: ['admin', 'teacher'] 
                },
                children:[
                    {
                        path: 'create',
                        component: () => import('../views/createExamSchedule/edit.vue'),
                        meta: {
                            title: '新增考试安排',
                            roles: ['admin', 'teacher'] 
                        }
                    }
                ]
            },
            {
                path: 'releaseExam',
                component: () => import('../views/releaseExam.vue'),
                meta: {
                    title: '发布考试',
                    roles: ['admin', 'teacher'] 
                }
            },
            {
                path: 'testPaperGrading',
                component: () => import('../views/testPaperGrading/index.vue'),
                meta: {
                    title: '试卷批改',
                    roles: ['admin', 'teacher']
                }
            },
            {
                path: 'testPaperGrading/Edit',
                component: () => import('../views/testPaperGrading/edit.vue'),
                meta: {
                    title: '试卷管理-批改',
                    roles: ['admin', 'teacher']
                }
            },
            {
                path: 'studentPerformanceAnalysis',
                component: () => import('../views/studentPerformanceAnalysis.vue'),
                meta: {
                    title: '学生成绩分析',
                    roles: ['admin', 'teacher'] 
                }
            },
            {
                path: "classManagement/teacher",
                component: () => import('../views/classManagement/teacher.vue'),
                meta: {
                    title: '添加班级',
                    roles: ['admin', 'teacher']
                }
            },
            {
                path: "classManagement/student",
                component: () => import('../views/classManagement/student.vue'),
                meta: {
                    title: '查看班级',
                    roles: ['admin', 'teacher']
                }
            }
        ],
    },
    {
        path: '/',
        redirect: '/main/home'
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes,
})

// ================== 新增代码：全局路由守卫 ==================
router.beforeEach((to, _, next) => {
    // 获取 user store 实例
    // 注意：必须在守卫内部调用，而不是在顶层作用域，以确保获取的是最新的实例
    // 开始进度条
    NProgress.start()

    const userStore = useUserStore()

    const title = to.meta.title

    if (title) {
        document.title = title as string
    } else {
        document.title = '在线考试系统'
    }

    // 定义需要权限的页面路径
    // 这里我们简单判断，只要不是登录页，就需要权限
    const requiresAuth = to.path !== '/login'

    // 情况一：用户已登录 (token 存在)
    if (userStore.userInfo.token) {
        // 如果已登录，但还想去登录页，那么直接重定向到主页
        if (to.path === '/login') {
            next('/main/home') // 可以直接跳转到主页的某个子页面，如 home
        } else {
            // 否则，放行，允许他去任何他想去的页面
            next()
        }
    }
    // 情况二：用户未登录 (token 不存在)
    else {
        // 如果他想访问需要权限的页面
        if (requiresAuth) {
            // 强制跳转到登录页
            next('/login')
        } else {
            // 如果他本来就是要去登录页，那就放行
            next()
        }
    }
})

// 全局后置钩子
router.afterEach(() => {
    // 结束进度条
    NProgress.done()
})

export default router
